<?php

/**
 * 支付宝开放平台
 */

namespace Service\AlipayOpenPlatform;

define("AOP_SDK_WORK_DIR", DIR_LOGS); // win环境下不加会 invalid [default store dir]: /tmp/ ？？？
require('AopSdk.php');

class AopFactory
{
    /**
     * @var \AopClient $aop
     */
    private $sandbox_aop;

    /**
     * @var \AopClient $aop
     */
    private $production_aop;

    /**
     * 沙箱
     *
     * @return \AopClient
     */
    public function sandboxAop()
    {
        if (! $this->sandbox_aop) {
            //
            $this->sandbox_aop = new \AopClient;
            // @link https://openhome.alipay.com/platform/appDaily.htm?tab=info - 沙箱网关
            //        $this->sandbox_aop->gatewayUrl = 'https://openapi.alipaydev.com/gateway.do';
            //        $this->sandbox_aop->appId = 'TODO';
            //        $this->sandbox_aop->rsaPrivateKey = file_get_contents(app_path('certs/ali/open_platform/panx_private.key'));
            //        $this->sandbox_aop->alipayrsaPublicKey = file_get_contents(app_path('certs/ali/open_platform/alipay_public_sandbox.key'));
            //        $this->sandbox_aop->signType = "RSA2";
        }

        return $this->sandbox_aop;
    }

    /**
     * 真实 pc端
     *
     * @param \Config $config
     *
     * @return \AopClient
     */
    public function productionAop(\Config $config)
    {
        if (! $this->production_aop) {
            $this->production_aop = new \AopClient;
            $this->production_aop->appId = $config->get('oauth_alipay_pc_app_id');
            $this->production_aop->rsaPrivateKey =  $config->get('oauth_alipay_pc_private_key');
            $this->production_aop->alipayrsaPublicKey = $config->get('oauth_alipay_pc_public_key');
            $this->production_aop->signType = "RSA2";
        }

        return $this->production_aop;
    }

    /**
     * app端的账号登录
     *
     * @param array $alipay_config
     * @return \AopClient
     */
    public function productionAppAop(array $alipay_config)
    {
        if (! $this->production_aop) {
            $this->production_aop = new \AopClient();
            $this->production_aop->appId = $alipay_config['app_id'];
            $this->production_aop->rsaPrivateKey = $alipay_config['app_private_key'];
            $this->production_aop->alipayrsaPublicKey= $alipay_config['app_public_key'];
            $this->production_aop->pid = $alipay_config['pid'] ?? '';
            $this->production_aop->signType = 'RSA2';
        }

        return $this->production_aop;
    }
}